package org.dei.perla.rockfall.utils;

public class Synchronizer implements Runnable {

	private static int stopNotifications;
	private static int startNotifications;
	private static int numThreads;
	
	private static Object syncPrint;
	private static Object syncStart;
	
	public Synchronizer(int num) {
		stopNotifications = 0;
		startNotifications = 0;
		numThreads = num;
		syncPrint = new Object();
		syncStart = new Object();
	}
	
	public static void fpcFinished() {
		synchronized (syncPrint) {
			stopNotifications++;
			syncPrint.notify();
		}
	}
	
	public static void waitStart() {
		synchronized (syncStart) {
			try {
				syncStart.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void generatorFinished() {
		synchronized (syncStart) {
			startNotifications++;
			if (startNotifications == numThreads) {
				syncStart.notifyAll();
			}
		}
	}
	
	public void run() {
		synchronized (syncPrint) {
			while (numThreads > stopNotifications) {
				try {
					System.out.println("Waiting");
					syncPrint.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		TimeElapsed.printTimes();
	}
}
